export interface RI extends RequestInit {
  params?: any;
}
export const defHttp = (url: string, options?: RI) => {
  return new Promise(async (resolve, reject) => {
    const controller = new AbortController();
    const tid = setTimeout(() => {
      console.error(`Fetch timeout: ${newUrl}`);
      controller.abort();
      reject();
    }, 1000);
    const newUrl = combineUrlParams(parseProxyServer(url), options);
    console.log(newUrl);
    const response = await fetch(newUrl, {
      ...(options || {}),
      signal: controller.signal,
    }).then((r) => r.json());
    clearTimeout(tid); // 得到请求结果后，要清除定时器
    if (response.code == 200 || response.code == 0) {
      resolve(response);
    }
    reject();
  });
};

const parseProxyServer = (url: string) => {
  return "http://127.0.0.1:8083" + url;
};

const combineUrlParams = (url: string, options?: RI) => {
  if (options?.params) {
    const str = Object.keys(options.params)
      .reduce((p: any, c: any) => {
        p.push(`${c}=${options.params[c]}`);
        return p;
      }, [])
      .join("&");
    return url + "?" + str;
  }
  return url;
};
